package com.filepd.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.filepd.dto.LoginUser;
import com.filepd.dto.UserDto;
import com.filepd.entity.User;
import com.filepd.service.LoginService;
import com.filepd.service.UserService;
import com.filepd.utils.JwtUtil;
import com.filepd.utils.RedisCache;
import com.filepd.utils.WeBASEUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserService userService;

    /**
     * 注册的时候用 ,加密
     */
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private WeBASEUtils weBASEUtils;


    /**
     * 登录
     *
     * @param user
     * @return
     */
    @Override
    public UserDto login(User user) {
        UserDto userDto = new UserDto();
        //用户传来的封装
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                user.getUserAccount(), user.getUserPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        if (Objects.isNull(authenticate)) {
            return null;
        }

        //使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);

        //authenticate存入redis
        redisCache.setCacheObject(userId, loginUser);

        //把token响应给前端并设置user权限
        userDto.setUserName(loginUser.getUsername());
        userDto.setUserPhone(loginUser.getUser().getUserAccount());
        userDto.setUserRole(loginUser.getUser().getUserRole());
        userDto.setToken(jwt);

        userDto.setId(loginUser.getUser().getId());
        return userDto;
    }

    /**
     * 退出登录
     */
    @Override
    public void logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        //从Redis中删除
        redisCache.deleteObject(Collections.singleton(principal));
        System.out.println(principal);
    }

    /**
     * 注册
     *
     * @param user
     * @return
     */
    @Override
    public boolean register(User user) {
        //不存在返回true
        //根据页面提交的手机号查询数据库user
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //判断是否在数据库中存在
        User one = userService.getOne(queryWrapper
                .eq(User::getUserAccount, user.getUserAccount()));

        //拿到匹配的数据
        //如果没有查询到则返回注册失败结果
        if (one != null) {
            return false;
        }

        //HmacSHA256进行加密
        String password = user.getUserPassword();
        String encode = passwordEncoder.encode(password);
        user.setUserPassword(encode);

        //设置默认值
        user.setUserRole("user");

        //数据上链
        weBASEUtils.PublicAndPrivateKey_generationUtils(user.getUserName());
        //保存
        userService.save(user);
        return true;
    }
}
